
var models = require('../db')
var express = require('express')
var router = express.Router()
var mysql = require('mysql')
var $sql = require('../sqlMap')
var app = express()
var jwt = require('jsonwebtoken')

// 使用连接池链接数据库
var pool = mysql.createPool(models.mysql)
var conn = mysql.createConnection(models.mysql)

conn.connect()
// var jsonWrite = function (res, ret) {
//   if(typeof ret === 'undefined') {
//       res.json({
//           code: '1',
//           msg: '操作失败'
//       })
//   } else {
//       res.json(ret)
//   }
// }
conn.end()

router.use(function (req, res, next) {
  // 輸出記錄訊息至終端機
  console.log(req.method, req.url)
  // 繼續路由處理
  next()
})

function callback (err, req, res) {
  if (err) {
    conn.rollback(function () {// 如果失败回滚
      res.json({
        code: 0,
        error: err,
        msg: ('哎呀出錯了..数据已经回滚')
      })
    })
  } else {
    conn.commit(function (err2) {  
      if (err2) {
        conn.rollback(function () {
          res.json({
            code: 0,
            error: err2,
            msg: ('操作提交失败..請稍後再試哦')
          })
        })
      }
    })
  }
}
async function nextQuery (sql, arg=[], obj) {
  return new Promise((resolve, reject) => {
    pool.query(sql, arg, (error, r1) => {
      if (error) {
        reject(error)
      } else {
        if (!obj) {
          resolve(r1)
        } else {
          let res = Object.assign(r1, {book: obj})
          console.log('我在这里')
          console.log(res)
          resolve(res)
        }
      }
    })
  })
}

router.use('/login', (req, res) => {
  var sql = $sql.user.login
  var params = req.body // req.body获取form提交参数，post请求
  // console.log(params)
  pool.query(sql, [params.id, params.pwd], (error, results, fields) => {
    if (error) {
      return res.json({
        code: 0,
        error: error,
        msg: ('哎呀出錯了..請稍後再試哦')
      })
    }else if (results) {
      if (results.length === 0) {
        return res.json({
          code: 1,
          msg: ('手机号或密码错误了...')
        })
      } else {
        console.log('正确返回数据')
        console.log(results)
        let token = jwt.sign({id: params.id, pwd: params.pwd}, models.secret, {
          expiresIn: 60 * 60 * 24 // 设置过期时间
        })
        return res.json({
          code: 2,
          token: token,
          msg: ('欢迎你~')
        })
      }
    }
  })
})

router.use('/register', (req, res) => {
  var sql = $sql.user.register
  var params = req.body // req.body获取form提交参数，post请求
  console.log(params)
  pool.query(sql, [params.id, params.pwd], (error, results, fields) => {
    if (error) {
      callback(error,req,res)
    } else {
      console.log('正确返回数据')
      console.log(results)
      let sql2 = $sql.user.addInfo
      pool.query(sql2, [params.id ,params.name], (error, results, fields) => {
        if (error) {
          callback(error, req, res)
        } else {
          let token = jwt.sign({id: params.id,pwd: params.pwd}, models.secret, {
            expiresIn: 60 * 60 * 24 // 设置过期时间
          })
          callback(null, req, res)
          return res.json({
            code: 2,
            token: token,
            msg: ('欢迎你~')
          })
        }
      })
    }
  })
})

router.get('/search', (req, res) => {
  var params = req.query 
  var sql
  console.log(req.query)// req.query获取url的查询参数
  console.log('sid:'+ params.sid)
  console.log('search:'+ params.search)
  if (params.sid === 0) {
    if (params.search=='all') {
      sql = $sql.search.all
    } else sql = $sql.search.book
  } else if (params.sid === 1) {
    sql = $sql.search.author
  } else {
    sql = $sql.search.type
  }
  pool.query(sql, [params.search], (error, results, fields) => {
    if (error) {
      return res.json({
        code:0,
        error:error,
        msg:('哎呀出錯了..請稍後再試哦')
      })
    } else if (results) {
      if (results.length==0) {
        return res.json({
          code: 1,
          msg: ('暫時還沒有相應結果')
        })
      } else {
        console.log(results)
        return res.json({
          code: 2,
          msg: ('快來看看有沒有你想要的！'),
          data: results
        })
      }
    }
  })
})

router.get('/getCart',(req,res)=>{
    let token = req.get("Authorization").split('Bearer ').join('')
    console.log("token:"+token)
    if(token){
        let t=token.substring(1,token.length-1)
        console.log(t)
        jwt.verify(t,models.secret,function(error, decoded){
            if(error){
                return res.json({
                    code:-1,
                    error:error,
                    msg:('登录信息已过期，请重新登录')
                })
            }else{
                console.log(decoded)
                var sql=$sql.cart.search
                pool.query(sql,[decoded.id],(error, results, fields)=>{
                    if(error){                
                        return res.json({
                            code:0,
                            error:error,
                            msg:('哎呀出錯了..請稍後再試哦')
                        })
                    }
                    else if(results){
                        if(results.length==0){
                            return res.json({
                                code:1,
                                msg:('购物车还没有东西呢~ 最近又上新了哦')
                            })
                        }else{
                            console.log(results)
                            return res.json({
                                code:2,
                                msg:('快來看看有沒有你想要的！'),
                                data:results
                            })
                        }
                    }
                })
            }
        })
    }
})

router.use('/changeCart',(req,res)=>{
    let token = req.get("Authorization").split('Bearer ').join('')
    console.log(token)
    if(token){
        let t=token.substring(1,token.length-1)
        console.log(t)
        jwt.verify(t,models.secret,function(error, decoded){
            if(error){
                return res.json({
                    code:-1,
                    error:error,
                    msg:('登录信息已过期，请重新登录')
                })
            }else{
                console.log(decoded)
                let sql
                let params=req.body
                let o=[]
                if(params.mid==='update'){
                    o.push(params.amount)
                    o.push(decoded.id)
                    o.push(params.bid)
                    sql=$sql.cart.update
                }else if(params.mid==='delete'){
                    o.push(decoded.id)
                    o.push(params.bid)
                    sql=$sql.cart.delete
                }else if(params.mid==='add'){
                    o.push(decoded.id)
                    o.push(params.bid)
                    o.push(params.amount)
                    sql=$sql.cart.add
                }
                console.log(req)
                console.log(o)
                pool.query(sql,o,(error, results, fields)=>{
                    if(error){
                        console.log('?')
                        callback(error,req,res)
                    }
                    else if(results){
                        callback(null,req,res)
                        return res.json({
                            code:1,
                            msg:('操作成功~'),
                            data:results
                        })
                    }
                })
            }
        })    
    }
    
})
router.use('/addOrder',(req,res)=>{
    let token=req.get("Authorization").split('Bearer ').join('')
    console.log(token)
    if(token){
        let t=token.substring(1,token.length-1)
        jwt.verify(t,models.secret,function(error,decoded){
            if(error){
                return res.json({
                    code:-1,
                    error:error,
                    msg:('登录信息已过期，请重新登录')
                })
            }else{
                console.log(decoded)
                let params=req.body
                let sql=$sql.orders.add
                console.log([decoded.id,params.aid,params.amount,params.total])
                pool.query(sql,[decoded.id,params.aid,params.amount,params.total],(error, order, fields)=>{
                    if(error){
                        console.log(error)
                        callback(error,req,res)
                    }else if(order){
                        let sql2=$sql.ordersDetail.add
                        for(let i=0;i<params.goods.length;i++){
                            let good=params.goods[i]
                            let bid=good.b_id.substring(1,token.length-1) 
                            console.log([order.insertId,bid,good.amount,good.total])
                            pool.query(sql2,[order.insertId,good.b_id,good.amount,good.total],(err, results, fields)=>{
                                if(err){
                                    console.log(err)
                                    callback(err,req,res)
                                }
                            })
                        }
                        return res.json({
                            code:1,
                            msg:('操作成功~'),
                            data:order.insertId
                        }) 
                    }
                })
            }
        })
    }
})

router.get('/getOrderlist',(req,res)=>{
    let token = req.get("Authorization").split('Bearer ').join('')
    console.log("token:"+token)
    if(token){
        let t=token.substring(1,token.length-1)
        console.log(t)
        jwt.verify(t,models.secret,function(error, decoded){
            if(error){
                return res.json({
                    code:-1,
                    error:error,
                    msg:('登录信息已过期，请重新登录')
                })
            }else{
                console.log(decoded)
                var sql=$sql.orders.searchAll
                nextQuery(sql,[decoded.id]).then(r1=>{
                    console.log('执行第一条sql成功')
                    console.log(r1)
                    if(r1.length==0){
                        return res.json({
                            code:1,
                            msg:('亲你还没下单呢~')
                        })
                    }else{
                        // let results=[]
                        let sql2=$sql.ordersDetail.search
                        let i=0
                        console.log('准备执行第二条语句')
                        let queryPromise= r1.map(item=>{
                            console.log('执行第二条语句')
                            return nextQuery(sql2,[item.id],item)
                                // .then(r2=>{
                                //     console.log('订单明细开始')
                                //     console.log(r2)
                                //     let o={
                                //         id:r1[i].id,
                                //         state:r1[i].state,
                                //         createtime:r1[i].createtime,
                                //         amount:r1[i].amount,
                                //         total:r1[i].total,
                                //         book:r2
                                //     }
                                //     results.push(o)
                                // })
                        })
                        Promise.all(queryPromise).then(results=>{
                            console.log('最后结果？')
                            console.log(results)
                            return res.json({
                                code:1,
                                msg:('操作成功~'),
                                data:results
                            })
                            console.log('结束')
                        }).catch(error=>{
                            console.log('出错')
                            console.log(error)
                            return res.json({
                                code:0,
                                error:error,
                                msg:('哎呀出錯了..請稍後再試哦')
                            })
                        })
                    }
                }).catch(error=>{
                    return res.json({
                        code:0,
                        error:error,
                        msg:('哎呀出錯了..請稍後再試哦')
                    })
                })
                
            }
        })
    }
})
router.get('/getOrder',(req,res)=>{
    let token = req.get("Authorization").split('Bearer ').join('')
    console.log("token:"+token)
    if(token){
        let t=token.substring(1,token.length-1)
        console.log(t)
        jwt.verify(t,models.secret,function(error, decoded){
            if(error){
                return res.json({
                    code:-1,
                    error:error,
                    msg:('登录信息已过期，请重新登录')
                })
            }else{
                console.log(decoded)
                var params=req.query 
                var sql=$sql.orders.searchOne
                pool.query(sql,[params.id],(error, order, fields)=>{
                    if(error){                
                        return res.json({
                            code:0,
                            error:error,
                            msg:('哎呀出錯了..請稍後再試哦')
                        })
                    }
                    else if(order){
                        if(order.length==0){
                            return res.json({
                                code:1,
                                msg:('亲你还没下单呢~')
                            })
                        }else{
                            console.log(order)
                            let sql2=$sql.ordersDetail.search
                            let results=[]
                            pool.query(sql,[order.id],(error, item, fields)=>{
                                if(error){                
                                    return res.json({
                                        code:0,
                                        error:error,
                                        msg:('哎呀出錯了..請稍後再試哦')
                                    })
                                }
                                else if(item){
                                    console.log(...item)
                                    let orderInfo={
                                        id:order[i].id,
                                        state:order[i].state,
                                        createtime:order[i].createtime,
                                        amount:order[i].amount,
                                        total:order[i].total,
                                        book:item
                                    }
                                    console.log(orderInfo)
                                }
                            })
                            return res.json({
                                code:1,
                                msg:('操作成功~'),
                                data:orderInfo
                            })
                        }
                    }
                })
            }
        })
    }
})
app.use('/', router)
module.exports = router
